package com.hwadee.service;

import com.hwadee.mapper.DoctorMapper;
import com.hwadee.mapper.ElderUserMapper;
import com.hwadee.mapper.OldinfoMapper;
import com.hwadee.pojo.ElderUser;
import com.hwadee.pojo.Oldinfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OldinfoService {

    @Autowired
    private OldinfoMapper oldinfoMapper;

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private ElderUserMapper elderUserMapper; // ✅ 注入 ElderUserMapper

    public List<Oldinfo> getlistOldinfo() {
        return oldinfoMapper.getlistOldinfo();
    }

    public void addOldinfo(Oldinfo oldinfo) {
        oldinfoMapper.addOldinfo(oldinfo);
    }

    public void delOldinfo(String id) {
        oldinfoMapper.delOldinfo(id);
    }

    public void updateOldinfo(Oldinfo oldinfo) {
        oldinfoMapper.updateOldinfo(oldinfo);
    }

    /**
     * 插入 oldinfo，同时插入 elder_user，并使用相同 id
     */
    @Transactional
    public void addOldInfoWithDoctorId(Oldinfo oldInfo) {
        // 1. 根据医生姓名查找 doctorId
        Integer doctorId = doctorMapper.findIdByName(oldInfo.getBoundDoctor());
        if (doctorId == null) {
            throw new RuntimeException("未找到绑定医生: " + oldInfo.getBoundDoctor());
        }

        oldInfo.setDoctorId(doctorId);

        // 2. 插入 oldinfo 表（自动生成 id）
        oldinfoMapper.addOldinfo(oldInfo); // 此处 id 会自动回填到 oldInfo.id（因为 useGeneratedKeys）

        // 3. 构造 elder_user 数据（手动构建）
        ElderUser user = new ElderUser();
        user.setId(Math.toIntExact(oldInfo.getId()));// ✅ 保证 id 相同（关联）
        user.setUsername(oldInfo.getName());
        user.setPhone(oldInfo.getContactPhone());
        user.setStatus("正常"); // 你可以根据需要赋值
        user.setRole("普通用户"); // 你也可以从前端传

        // 4. 插入 elder_user 表
        elderUserMapper.insert(user);
    }
}
